﻿#pragma once

#ifndef TCPBASE_H
#define TCPBASE_H

#include "netComm.h"
#include "asyncBase.h"

#ifdef _WIN32
#include <WinSock2.h>
#include <WS2tcpip.h>
#else

#include <sys/types.h>
#include <sys/socket.h>

#define SOCKET                  int32_t
#define INVALID_SOCKET  (SOCKET)(~0)
#define SOCKET_ERROR            (-1)

#define closesocket(a)	close(a)
#define WSACleanup()
#endif

#include <iostream>
#include <atomic>

class netTcpServer
{
public:
    explicit netTcpServer(cmdWorker* parser);
    ~netTcpServer();
    int netServerInit(int port);
    int netServerStop();
    int netServerSend(const uint8_t* data, int length);
protected:
    int sockSelect();
	int sockSelect(int fd,char* data,int length);

protected:
    std::atomic<SOCKET> serSockFD, cliSockFD;

    std::unique_ptr<ThreadHelper> thrHelper;

    uint8_t recvBuf[4096];
    int bufferUsed;

    cmdWorker* worker;
    std::mutex      mutexSend;
};


class netTcpClient {
public:
    explicit netTcpClient(cmdWorker* parser);
    ~netTcpClient();
    int netClientConnect(const char* ip, int port, int timeoutSec = 5);
    int netClientClose();
    int netClientRequire(const char * data, int length);
protected:
    int sockSelect();
	int sockSelect(int fd, char* data, int length);
    int connectTimeOut(SOCKET sockfd, const struct sockaddr *addr, int addrlen, int timeoutSec);


protected:
    std::atomic<SOCKET> cliSockFD;
    std::unique_ptr<ThreadHelper> thrHelper;

    uint8_t recvBuf[4096];
    int bufferUsed;

    cmdWorker*      worker;
    std::mutex      mutexSend;
};

#define SSDP_ADDR "239.255.255.250"  // SSDP多播地址
#define SSDP_PORT 1900  // SSDP端口

class netUdp {
public:
	explicit netUdp(cmdWorker* parser);
    ~netUdp();

	int netUdpInit(const char* ip, int port);
	int netUdpSend(const char * data, int length, const char* ip, int port);
    int netclose();
protected:
	int sockSelect();
	int sockSelect(int fd, char* data, int length);
protected:
	std::atomic<SOCKET> localSock;
//	std::unique_ptr<ThreadHelper> thrHelper;

	uint8_t recvBuf[4096];
	int bufferUsed;

	cmdWorker*      worker;
	std::mutex      mutexSend;
};

#endif
